<!--
 * @Author: Liz.Zheng
 * @Date: 2021-09-24 16:23:18
 * @LastEditTime: 2022-06-27 17:47:17
 * @LastEditors: 郑亚莉 zhengyali@shequ.life
 * @Description: 渲染入口
 * @Motto: Write the code. Change the world.
-->
<template>
  <a-config-provider :locale="locale">
    <!-- v-if="showApp" -->
    <!-- fontSize: '50px' -->
    <div
      id="workAI"
      class="hide-scroller-bar"
      :style="{
        ...appStyle,
        fontFamily: FF,
      }"
    >
      <router-view v-slot="{ Component }">
        <keep-alive :include="keepAliveRoutes">
          <component :is="Component" />
        </keep-alive>
      </router-view>

      <ElectronUpdater v-if="showElectronUpdater" />
    </div>
  </a-config-provider>
</template>

<script>
import { computed, ref, reactive, toRefs, watch } from "vue";
import store from "./store/index";
import actions from "./common/utils/action";
import i18n from "./locale/index";
import routes from "./router/router.config";
import utils from "./common/utils/utils";
import { useRoute, useRouter } from "vue-router";
import ElectronUpdater from "./views/updater/index.vue";
import axios from "axios";
import request from "@/common/utils/request.js";
import { message } from "ant-design-vue";
import { defaultOrg_id } from '@/common/utils/atherUtils.js'

export default {
  name: "app",
  components: {
    ElectronUpdater,
  },
  setup() {
    const state = reactive({
      web_state: import.meta.env.WEB_SITE,
      FF: "-apple-system, BlinkMacSystemFont,Segoe UI, Roboto,Helvetica Neue, Arial,Noto Sans, sans-serif,Apple Color Emoji,Segoe UI Emoji,Segoe UI Symbol,Noto Color Emoji",
    });

    // antdesign多语言
    const locale = computed(
      () => i18n.global.getLocaleMessage(store.getters.lang).antLocale
    );

    // 获取需要缓存的页面name
    let routesArr = [];
    utils.getKeepAliveRoutes(routes, routesArr);
    const keepAliveRoutes = ref(routesArr);

    // 设置和监听容器高度并作出适应
    const appStyle = computed(() => {
      if (store.getters.appHeight) {
        return {
          height: `${store.getters.appHeight}px`,
        };
      }
      return { height: `100%` };
    });

    const loadingRef = document.getElementById("pageLoading");
    if (loadingRef) {
      loadingRef.parentNode.removeChild(loadingRef);
    }

    const showElectronUpdater = computed(() => {
      return import.meta.env.ELECTRON;
      // && /windows|win32/i.test(navigator.userAgent)
    });

    const showApp = ref(false);

    const route = useRoute();
    const router = useRouter();

    const maskVisible = ref(false);

    
    const setLocationData = async () => {
      return new Promise(async (resolve, reject) => {
            // 获取当前 URL 的查询字符串部分
      const queryString = window.location.search;
      // 创建 URLSearchParams 对象
      const urlParams = new URLSearchParams(queryString);
      const scene_type = urlParams.get("scene_type");

      if (scene_type) {
        store.dispatch("SetScene_type", scene_type);
      } else {
        store.dispatch("SetScene_type", '');
      }

      // 获取 invite 参数的值
      const inviteCode = urlParams.get("invite");
      // 存储inviteCode
      if (inviteCode) {
        store.dispatch("SetInviteCode", inviteCode);
        localStorage.setItem("teamInviteCode", inviteCode);
      } else {
        store.dispatch("SetInviteCode", '');
        localStorage.setItem("teamInviteCode", '');
        }
        resolve()

      // debugger
      // 从 URL 中获取 org_id
      // let org_id = urlParams.get("org_id")
      // if (org_id) {
      //   await store.dispatch("SetOrgId", urlParams.org_id)
      //   const userInfo = await utils.getUserInfo();
      //     showApp.value = true;
      //     resolve()
      // } else {
      //   // 接口获取orgid
      //   try {
      //     const config = await store.dispatch("GetConfigInfo")
      //         if (!config?.basic?.can_reg_org) {
      //           org_id = defaultOrg_id
      //           } else {
      //             org_id = config?.basic?.oem_org_id ??
      //               config?.basic?.system_org_id ?? defaultOrg_id
      //           }
      //           store.dispatch("SetOrgId", org_id || defaultOrg_id)
      //           const userInfo = await utils.getUserInfo();
      //           showApp.value = true;
      //           resolve()
      //   } catch (error) {
      //     store.dispatch("SetOrgId", 1)
      //     showApp.value = true;
      //     resolve()
      //   }
      // }
      })
  
    };


    const init = async () => {

      let agent = navigator.userAgent.toLowerCase();
      let isMac = /macintosh|mac os x/i.test(navigator.userAgent);
      if (agent.indexOf("win32") >= 0 || agent.indexOf("wow32") >= 0) {
        state.FF =
          "Inter,-apple-system,BlinkMacSystemFont,Segoe UI,PingFang SC,Hiragino Sans GB,Microsoft YaHei,Helvetica Neue,Helvetica,Arial,sans-serif;";
      }
      if (agent.indexOf("win64") >= 0 || agent.indexOf("wow64") >= 0) {
        state.FF =
          "Inter,-apple-system,BlinkMacSystemFont,Segoe UI,PingFang SC,Hiragino Sans GB,Microsoft YaHei,Helvetica Neue,Helvetica,Arial,sans-serif;";
      }
      if (isMac) {
        state.FF =
          "Roboto,Helvetica,PingFang SC,Hiragino Sans GB,Microsoft YaHei,Arial,sans-serif,Helvetica Neue,-apple-system,BlinkMacSystemFont,noto sans";
      }

     await setLocationData();

      if (!utils.getUserToken()) {
        const urlLink = location.href;
        if (urlLink.includes("UseAgreement")) {
          return;
        } else if (urlLink.includes("PrivacyAgreement")) {
          return;
        } else {
          if (window.location.origin !== "https://v.kuaijing.cn") {
            router.push({ path: "/workShotstack/home" });
          } else {
            router.push({ path: "/workShotstack" });
          }
          return;
        }
      }

      // 通过分享链接打开时，移动设备自动跳转到移动端
      if (utils.isMobile()) {
        let baseUrl = location.origin;
        if (process.env.NODE_ENV === "development") {
          baseUrl = "https://chatgpt.kuaijingai.com";
        }
        if (location.hash.indexOf("?") != -1) {
          let query = "?" + location.hash.split("?")[1];
          window.location.href = baseUrl + "/h5" + query;
        } else {
          window.location.href = baseUrl + "/h5";
        }
      }

      if (utils.getStorage("tipCache_work_ai")) {
        maskVisible.value = false;
      } else {
        maskVisible.value = true;
      }

      let last_team = 0;
      for (let i = 0; i < localStorage.length; i++) {
        const key = localStorage.key(i);
        const match = key.match(new RegExp(`^LASTORG_(\\d+)_LASTUID_(\\d+)$`));

        const org_id = utils.getOrgId();
        if (match) {
          if(org_id != match[1]) {
            localStorage.removeItem(key);
          } else {
            const last_orgId = match[1];
            const last_uid = match[2];
            let now_orgId = utils.getOrgId();
            let now_uId = "";
  
            const now_userInfo = await utils.getUserInfo();
            if (now_userInfo.uid) {
              now_uId = String(now_userInfo.uid);
            }
            if (last_orgId == now_orgId && last_uid == now_uId) {
              last_team = localStorage.getItem(key);
              store.commit("SET_TEAM_ID", last_team);
            }
          }
        }
      }
    };
    init();

    // 标签关闭
    const tagClose = () => {
      maskVisible.value = false;
      utils.setStorage("tipCache_work_ai", true, false);
    };

    // watch(() => route, (newRoute) => {
    //   if(newRoute.query && newRoute.query.org_id ) {
    //      let org_id = newRoute.query.org_id
    //      localStorage.setItem("ORG_ID", org_id);
    //   }
    // }, { deep: true, immediate:true });


    return {
      ...toRefs(state),
      setLocationData,
      appStyle,
      locale,
      keepAliveRoutes,
      showApp,
      maskVisible,
      tagClose,
      showElectronUpdater,
      // getDefaultVoice
    };
  },
};
</script>

<style lang="less">
body,
#app {
  width: 100%;
  height: 100%;

  .mask-modal {
    position: absolute;
    top: 70px;
    right: 120px;

    .triangle {
      position: absolute;
      top: -10px;
      right: 20px;
      width: 0;
      height: 0;
      border-left: 10px solid transparent;
      border-right: 10px solid transparent;
      border-bottom: 15px solid white;
    }
  }
}

#__qiankun_microapp_wrapper_for_work_ai__ {
  height: 100%;
}
</style>
